package com.glitech.demo;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Json结果解析类
 */
public class JsonParser {

    public static class AsrResult {
        public String text;
        public int prob;
        public AsrResult() {
            this.text = "";
            this.prob = 0;
        }
    }

    public static AsrResult parseResult(String json) {
        AsrResult asrResult = new AsrResult();
        try {
            JSONTokener tokener = new JSONTokener(json);
            JSONObject joResult = new JSONObject(tokener);

            JSONArray words = joResult.getJSONArray("ws");
            for (int i = 0; i < words.length(); i++) {
                JSONArray items = words.getJSONObject(i).getJSONArray("cw");
                for (int j = 0; j < items.length(); j++) {
                    JSONObject obj = items.getJSONObject(j);
                    if (obj.getString("w").contains("nomatch")) {
                        return asrResult;
                    }
                    asrResult.text = obj.getString("w");
                    break;
                }
            }
            asrResult.prob = joResult.optInt("sc");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return asrResult;
    }
}
